﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using PluggableModulesInterface;
using StorageManagement;
using Settings;
using SMSROUTER.Business;
using System.Configuration;
using Utils;
using System.Data.Linq;
using PluggableModulesRouter;
using SMSROUTER.StorageManagement;

namespace MTRouterOneSmsBulkSms
{
    public class Router : WorkingBaseMTWebServiceRouter
    {
        #region Properties and Fields
        private WSOneSms.Service _SmsRouterObject = new WSOneSms.Service();
        protected override System.Web.Services.Protocols.SoapHttpClientProtocol SmsRouterObject
        {
            get
            {
                return _SmsRouterObject;
            }
        }
        public string UserName
        {
            get
            {
                return GetConfig("UserName");
            }
            set
            {
                SetConfig("UserName", value);
            }
        }
        public string Password
        {
            get
            {
                return GetConfig("Password");
            }
            set
            {
                SetConfig("Password", value);
            }
        }
        const string _dateTimeFormatString = "MMM d yyyy h:mtt";
        #endregion

        protected override void SendSms(List<SmsOutWaiting> smsOut)
        {
            int threadId = ThreadID;
            bool enableGetReport = ENABLE_GETREPORT;
            bool logToText = this.EnableLogToText;
            List<SmsRouterReport> listRouterReport = new List<SmsRouterReport>();
            foreach (var item in smsOut)
            {
                try
                {
                    string result = (SmsRouterObject as WSOneSms.Service).SendMT(UserName, Password, item.Message, item.ShortCode, item.DestAddr, false, item.Message.ContainsUnicodeCharacter());
                    if (!string.IsNullOrWhiteSpace(result))
                    {
                        if (result.StartsWith("Successfull_", StringComparison.CurrentCultureIgnoreCase))//Thành công
                        {
                            SmsOutReportStorage.EnqueueElementData(Key, new SmsOutReportStruct(item.RouterID, item.SmsOutGUID, item.CooperateGUID, DateTime.Now, DateTime.Now, item.RetryOnFailReqTimes, item.RetryOnTimeOutReqTimes, AppSetting.Status.SENTGATEWAY, threadId));
                            if (enableGetReport)
                            {
                                string cid = result.Substring(result.IndexOf("_") + 1);
                                listRouterReport.Add(new SmsRouterReport(item.RouterID, item.SmsOutGUID, item.CooperateGUID, DateTime.Now, null, AppSetting.Status.SENTGATEWAY, threadId, cid, null));
                            }
                        }
                        else//fail
                        {
                            SmsOutReportStorage.EnqueueElementData(Key, new SmsOutReportStruct(item.RouterID, item.SmsOutGUID, item.CooperateGUID, DateTime.Now, DateTime.Now, item.RetryOnFailReqTimes, item.RetryOnTimeOutReqTimes, AppSetting.Status.FAIL, threadId));
                            Log.InsertLog(string.Format("[SmsOutGUID = {0}] erorr: {1}", item.SmsOutGUID, result), "WSOneSms.Service.SentMT", ObjectType, AppSetting.WarningType.mt_error, item.CooperateID);
                        }
                    }
                    if (logToText)
                    {
                        Log.LogToText(item.SmsOutGUID, result, AppSetting.RouterType.MTROUTER);
                    }
                }
                catch (Exception ex)
                {
                    HandleException<SmsOutWaiting>(ex, AppSetting.WarningType.mt_error, item);
                }
            }
            //Insert dữ liệu report
            if (listRouterReport.Count > 0)
            {
                SmsRouterReport.BulkInsert(listRouterReport);
            }
        }

        protected override void GetReport()
        {
            long startID = 1;
            List<SmsRouterReport> listRouterReport = new List<SmsRouterReport>();
            do
            {
                listRouterReport = SmsRouterReport.GetByRouterID(this.Key, startID, this.BatchSize);
                if (listRouterReport.Count > 0)
                {
                    startID = listRouterReport[listRouterReport.Count - 1].ReportID + 1;
                    foreach (SmsRouterReport item in listRouterReport)
                    {
                        try
                        {
                            string result = (SmsRouterObject as WSOneSms.Service).GetReport(this.UserName, this.Password, item.StringParam);
                            string[] sArray = result.Split('|');
                            if (sArray.Length >= 2)
                            {
                                string reportStatus = sArray[0], reportTime = sArray[1];
                                if (!string.IsNullOrEmpty(reportStatus))
                                {
                                    switch (reportStatus)
                                    {
                                        case "DELIVERED":
                                            item.Status = AppSetting.Status.SENT;
                                            try
                                            {
                                                item.ReportTime = DateTime.Parse(reportTime);
                                            }
                                            catch (Exception)
                                            {
                                                Log.InsertLog(string.Format("[SmsOutGUID = {0}] reportTime error: {1}", item.SmsOutGUID, reportTime), "WSOneSms.Service.GetReport", ObjectType, AppSetting.WarningType.mt_error, null);
                                            }
                                            break;
                                        default:
                                            item.Status = AppSetting.Status.FAIL;
                                            try
                                            {
                                                item.ReportTime = DateTime.Parse(reportTime);
                                            }
                                            catch (Exception)
                                            {
                                                Log.InsertLog(string.Format("[SmsOutGUID = {0}] reportTime error: {1}", item.SmsOutGUID, reportTime), "WSOneSms.Service.GetReport", ObjectType, AppSetting.WarningType.mt_error, null);
                                            }
                                            Log.InsertLog(string.Format("[SmsOutGUID = {0}] erorr: {1}", item.SmsOutGUID, result), "WSOneSms.Service.GetReport", ObjectType, AppSetting.WarningType.mt_error, null);
                                            break;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            HandleException<SmsRouterReport>(ex, AppSetting.WarningType.mt_error, item);
                        }
                    }
                    SmsRouterReport.BatchUpdate(listRouterReport);
                }
            }
            while (listRouterReport.Count > 0);
        }
    }
}